import { useContext } from "react";
import { Link, Outlet, useNavigate } from "react-router-dom";
import { AppContext } from "../Context/AppContext";
export default function Layout() {
  const {user,token,setUser,setToken} = useContext(AppContext)
  const navigate = useNavigate()
  const handleLogout = async (e) => {
    e.preventDefault();
    
    const res = await fetch("/api/logout", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${token}`,
      },
    });
    
    // const data = await res.json()
    if (res.ok) {
      setUser(null)
      setToken(null)
      localStorage.removeItem("token");
      navigate('/')
    }
  };
  return (

    <>
        <header>
      <nav>
        <Link to="/" className="nav-link">
          Home
        </Link>
        {user?(
          <div className="space-x-4 flex flex-row items-center">
            <p className="text-slate-400 text-xs">欢迎:{user.name}</p>
             <Link className="nav-link" to='/create'>新建文章</Link>
            <form onSubmit={handleLogout}>
              <button  className="nav-link">退出</button>
            </form>
          </div>):( <div className="space-x-4">
          <Link className="nav-link" to='/register'>注册</Link>
          <Link className="nav-link" to='/login'>登录</Link>
          </div>)}
       
   </nav>
    </header>
        <main>
        <Outlet />
      </main>
    </>
  );
}
